<template>
  <div class="order-manage">
    <!-- 顶部搜索和筛选 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="订单号">
          <el-input v-model="filterForm.orderId" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="航班号">
          <el-input v-model="filterForm.flightNumber" placeholder="请输入航班号" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="待支付" value="PENDING"></el-option>
            <el-option label="已支付" value="PAID"></el-option>
            <el-option label="已完成" value="COMPLETED"></el-option>
            <el-option label="已取消" value="CANCELLED"></el-option>
            <el-option label="退款中" value="REFUNDING"></el-option>
            <el-option label="已退款" value="REFUNDED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="order-list">
      <div slot="header" class="clearfix">
        <span>订单列表</span>
        <el-button-group style="float: right">
          <el-button size="small" type="success" @click="handleBatchApprove" :disabled="!selectedOrders.length">
            批量同意
          </el-button>
          <el-button size="small" type="danger" @click="handleBatchCancel" :disabled="!selectedOrders.length">
            批量取消
          </el-button>
        </el-button-group>
      </div>

      <el-table
        v-loading="loading"
        :data="orders"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="orderId" label="订单号" width="120"></el-table-column>
        <el-table-column prop="flightNumber" label="航班号" width="100"></el-table-column>
        <el-table-column label="航线" width="200">
          <template slot-scope="scope">
            {{ scope.row.departureCity }} - {{ scope.row.arrivalCity }}
          </template>
        </el-table-column>
        <el-table-column prop="departureTime" label="起飞时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.departureTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="ticketType" label="票型" width="100"></el-table-column>
        <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
        <el-table-column prop="totalAmount" label="金额" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleViewDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === 'REFUNDING'"
              size="mini"
              type="success"
              @click="handleApprove(scope.row)"
            >
              同意
            </el-button>
            <el-button
              v-if="['PENDING', 'PAID', 'REFUNDING'].includes(scope.row.status)"
              size="mini"
              type="danger"
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="dialogVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="航班号">{{ currentOrder.flightNumber }}</el-descriptions-item>
        <el-descriptions-item label="航线">
          {{ currentOrder.departureCity }} - {{ currentOrder.arrivalCity }}
        </el-descriptions-item>
        <el-descriptions-item label="起飞时间">
          {{ formatDateTime(currentOrder.departureTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="到达时间">
          {{ formatDateTime(currentOrder.arrivalTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="票型">{{ currentOrder.ticketType }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ currentOrder.quantity }}</el-descriptions-item>
        <el-descriptions-item label="总金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">
          {{ formatDateTime(currentOrder.createTime) }}
        </el-descriptions-item>
      </el-descriptions>

      <div class="passenger-info" v-if="currentOrder.passengers">
        <h3>乘客信息</h3>
        <el-table :data="currentOrder.passengers" border style="width: 100%">
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="idCard" label="身份证号" width="180"></el-table-column>
          <el-table-column prop="phone" label="手机号" width="140"></el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'OrderManage',
  data() {
    return {
      loading: false,
      filterForm: {
        orderId: '',
        flightNumber: '',
        status: '',
        dateRange: []
      },
      orders: [],
      selectedOrders: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      currentOrder: {}
    }
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    async fetchOrders() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          orderId: this.filterForm.orderId,
          flightNumber: this.filterForm.flightNumber,
          status: this.filterForm.status,
          startDate: this.filterForm.dateRange[0],
          endDate: this.filterForm.dateRange[1]
        }

        const response = await axios.post('/manage/orders/list', params)
        if (response.data.code === 0) {
          this.orders = response.data.data.list
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.msg || '获取订单列表失败')
        }
      } catch (error) {
        console.error('Error fetching orders:', error)
        this.$message.error('网络错误，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    formatDateTime(datetime) {
      return moment(datetime).format('YYYY-MM-DD HH:mm')
    },
    getStatusType(status) {
      const statusMap = {
        'PENDING': 'warning',
        'PAID': 'success',
        'COMPLETED': 'success',
        'CANCELLED': 'info',
        'REFUNDING': 'warning',
        'REFUNDED': 'info'
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待支付',
        'PAID': '已支付',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消',
        'REFUNDING': '退款中',
        'REFUNDED': '已退款'
      }
      return statusMap[status] || status
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchOrders()
    },
    resetFilter() {
      this.filterForm = {
        orderId: '',
        flightNumber: '',
        status: '',
        dateRange: []
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchOrders()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchOrders()
    },
    handleSelectionChange(val) {
      this.selectedOrders = val
    },
    async handleViewDetail(order) {
      try {
        const response = await axios.post(`/manage/orders/${order.orderId}/detail`)
        if (response.data.code === 0) {
          this.currentOrder = response.data.data
          this.dialogVisible = true
        } else {
          this.$message.error(response.data.msg || '获取订单详情失败')
        }
      } catch (error) {
        console.error('Error fetching order detail:', error)
        this.$message.error('网络错误，请稍后重试')
      }
    },
    async handleApprove(order) {
      try {
        await this.$confirm('确定要同意此退款申请吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await axios.post(`/manage/orders/${order.orderId}/approve`)
        if (response.data.code === 0) {
          this.$message.success('退款申请已同意')
          this.fetchOrders()
        } else {
          this.$message.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Error approving order:', error)
          this.$message.error('网络错误，请稍后重试')
        }
      }
    },
    async handleCancel(order) {
      try {
        await this.$confirm('确定要取消此订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await axios.post(`/manage/orders/${order.orderId}/cancel`)
        if (response.data.code === 0) {
          this.$message.success('订单已取消')
          this.fetchOrders()
        } else {
          this.$message.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Error canceling order:', error)
          this.$message.error('网络错误，请稍后重试')
        }
      }
    },
    async handleBatchApprove() {
      if (!this.selectedOrders.length) return
      
      try {
        await this.$confirm(`确定要同意这 ${this.selectedOrders.length} 个退款申请吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const orderIds = this.selectedOrders.map(order => order.orderId)
        const response = await axios.post('/manage/orders/batch-approve', { orderIds })
        if (response.data.code === 0) {
          this.$message.success('批量同意成功')
          this.fetchOrders()
        } else {
          this.$message.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Error batch approving orders:', error)
          this.$message.error('网络错误，请稍后重试')
        }
      }
    },
    async handleBatchCancel() {
      if (!this.selectedOrders.length) return
      
      try {
        await this.$confirm(`确定要取消这 ${this.selectedOrders.length} 个订单吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const orderIds = this.selectedOrders.map(order => order.orderId)
        const response = await axios.post('/manage/orders/batch-cancel', { orderIds })
        if (response.data.code === 0) {
          this.$message.success('批量取消成功')
          this.fetchOrders()
        } else {
          this.$message.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Error batch canceling orders:', error)
          this.$message.error('网络错误，请稍后重试')
        }
      }
    }
  }
}
</script>

<style scoped>
.order-manage {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.order-list {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.passenger-info {
  margin-top: 20px;
}

.passenger-info h3 {
  margin-bottom: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style> 